package com.chunlin.servlet.cookieandseesion;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

class UserInfo {
    private String username;
    private long timestamp;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
}

@WebServlet("/getUserInfo")
public class IndexServlet extends HttpServlet {
    private  static final Logger logger = LoggerFactory.getLogger(IndexServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);

        UserInfo userInfo = new UserInfo();

        logger.info("666666");
        logger.error("77777");
        userInfo.setUsername((String) session.getAttribute("username"));
        userInfo.setTimestamp((long) session.getAttribute("timestamp"));

        ObjectMapper objectMapper = new ObjectMapper();
        String respJson = objectMapper.writeValueAsString(userInfo);
        //记得进行设置ContentType,不然前端不认识我们传递的json字符串
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(respJson);
    }
}
